<?php
/*
 * @Author: CHINAKAIYUAN<sunkaiyuan@namenode.cn>
 * @Date: 2022-02-02 19:42:06
 * @LastEditTime: 2023-10-17 16:39:12
 * @LastEditors: 孙开源 && sunkaiyuan@namenode.cn
 * @Description: 
 */

namespace App\Repositories;

use App\Models\Material;
use App\Models\ProPlanStorage;
use App\Models\ProPot;
use App\Models\ProPotRawSend;
use App\Models\MpcSummaryStorage;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Storage;
use Intervention\Image\Facades\Image;

/**
 * @property MpcSummaryStorage $storage
 * @property ProPotRawSendStorageRepository $raw_storage
 */
class ProPotRawSendRepository extends Repositories
    {
    public $relation_models = ['color', 'material', 'creator', 'status'];
    public function boot(ProPotRawSend $model, MpcSummaryStorage $storage, ProPotRawSendStorageRepository $raw_storage)
        {
        $this->model       = $model;
        $this->storage     = $storage;
        $this->raw_storage = $raw_storage;
        }

    public function getAddRawReport($ids)
        {
        $xml = $this->model->whereIn("id", $ids)->get()->map(function ($raw_send)
            {
            $pot = $raw_send->pro_pot;

            $data['rscraft_rename'] = $pot->rscode;
            $data['dyelot']        = $pot->dyelot;
            $data['customer_name'] = $pot->company_name;
            $data['color_code'] = $pot->color->code;
            $data['color_name'] = $pot->color->name;
            $data['quantity']  = $pot->yarn_quantity;
            $data['loom_name'] = $pot->loom->name;
            $data['lot_name'] = $pot->lot_name;
            //假设并缸，一个回修，就全部回修
            $pot->pro_plan->filter(function ($plan) use (&$data)
                {
                if ($plan->pro_yarn?->isrepair == 1)
                    $data['reform_name'] = "回修";
                });

            $data['dgremark']      = $pot->dgremark;
            $data['customeremark'] = $pot->remark;
            $data['material_name'] = $pot->material->name;
            $data['material_spec'] = $pot->material->spec;
            $data['printer'] = auth()->user()->name;

            if ($raw_send && $raw_send->state == 2) {
                $data['code']   = $raw_send->code;
                $data['zjcost'] = $raw_send->zjcost;
                $data['rlcost'] = $raw_send->rlcost;

                $data = $raw_send->details->map(function ($raw) use ($data)
                    {
                    $data['procedure']  = $raw->procedure;
                    $data['raw_code']   = $raw->material->code;
                    $data['raw_name']   = $raw->material->name;
                    $data['rate']       = (float) $raw->rate;
                    $data['qty']        = (float) $raw->quantity;
                    $data['uunit_name'] = $raw->uunit->name;
                    $data['remark'] = $raw->remark;
                    return $data;
                    });
                }
            else {
                $data = [$data];
                }
            return createReport($data);
            });
        return implode("", $xml->toArray());
        }
    /**
     * 创建加料单
     * @param mixed $pot_id
     * @param mixed $material_id
     * @param mixed $dyelot
     * @param mixed $color_id
     * @param mixed $quantity
     * @param mixed $items
     * @param mixed $state 1:染化料单，2::加料单
     * @return mixed
     * @author sunkaiyuan
     */
    public function createSend($pot_id, $material_id, $dyelot, $color_id, $quantity, $items, $state = 1)
        {
        $data['pro_pot_id']  = $pot_id;
        $data['material_id'] = $material_id;
        $data['dyelot']      = $dyelot;
        $data['color_id']    = $color_id;
        $data['quantity']    = $quantity;
        $data['state']       = $state;
        $data['cost']        = 0;
        $data['rl_cost']     = 0;
        $data['zj_cost']     = 0;
        $data['details']     = array_map(function ($item) use (&$data)
            {
            unset($item['id']);
            $spec = Material::whereId($item['material_id'])->value("spec");

            if (in_array(substr($spec, 0, 1), [1, 2, 3, 4])) {
                $data['rl_cost'] += $item['cost'];
                }
            else
                $data['zj_cost'] += $item['cost'];

            return $item;
            }, $items);
        $data['cost']    = $data['zj_cost'] + $data['rl_cost'];
        return $this->autosave($data);
        }
    public function outStorage(ProPotRawSend $model)
        {
        $model->status_id == 0 &&
            $model->details?->filter(function ($raw, $key) use ($model)
                {
                //$raw->uunit_id ==1  g 转kg 除1000,1999-999*1=1000,$raw->uunit_id ==2   kg 除1,1999-999*2=1999-1998=1
                $quantity = $raw->quantity / (1999 - 999 * $raw->uunit_id); //换算KG
                $this->setStorageData($raw->material_id, $quantity, $raw->main_id, $raw->id, $raw->pro_pot_id, $key + 1, $model);
                });
        $model->status_id = 1;
        $this->setPotCost($model);
        $model->save();
        }

    private function setPotCost(ProPotRawSend $model, $direct = 1)
        {
        $pro_pot          = $model->pro_pot;
        $pro_pot->rl_cost += $model->rl_cost * $direct;
        $pro_pot->zj_cost += $model->zj_cost * $direct;
        //计算加料次数
        if ($model->state == 2)
            $pro_pot->count_raw_add += $direct;
        $pro_pot->save();
        }
    public function nooutStorage(ProPotRawSend $model)
        {
        $model->status_id == 1 &&
            $model->storage?->filter(function ($storage)
                {
                $storage->nosubStorage();
                $storage->nouseStorage();
                $storage->delete();
                });
        $model->status_id = 0;
        $this->setPotCost($model, -1);
        $model->save();
        }

    private function setStorageData($material_id, $quantity, $main_id, $detail_id, $pro_pot_id, $num, $model)
        {
        $data['detail_id']  = $detail_id;
        $data['raw_id']     = $main_id;
        $data['pro_pot_id'] = $pro_pot_id;

        $this->storage
            ->where("material_id", $material_id)
            ->whereNotIn("location_id", [513, 514, 659]) // 染料南仓库	513 染料北仓库	514  染料仓库	659
            ->orderBy("available_quantity")
            ->get()
            ->map(function ($storage) use (&$quantity, $data, $model)
                {
                if ($quantity > 0) {
                    $data['dyelot']      = $storage->dyelot;
                    $data['lot_id']      = $storage->lot_id;
                    $data['location_id'] = $storage->location_id;
                    $data['color_id']    = $storage->color_id;
                    $data['unit_id']     = $storage->unit_id;
                    $data['company_id']  = $storage->company_id;
                    $data['type_id']     = $storage->type_id;
                    $data['iscustomer']  = $storage->iscustomer;
                    $data['material_id'] = $storage->material_id;

                    if ($quantity >= $storage->available_quantity) {
                        $quantity                   = $quantity - $storage->available_quantity;
                        $data['quantity']           = $storage->available_quantity;
                        $data['auxiliary_quantity'] = $storage->available_auxiliary_quantity;
                        $quantity -= $storage->available_quantity;
                        }
                    else {
                        $data['quantity']           = $quantity;
                        $data['auxiliary_quantity'] = $storage->available_auxiliary_quantity == 0 ? 0 : $quantity / ($storage->available_quantity / $storage->available_auxiliary_quantity);
                        $quantity                   = 0;
                        }
                    $rawstorage = $this->raw_storage->autosave($data);
                    $rawstorage->useStorage("生产领料", $model->code);
                    $rawstorage->subStorage();
                    }
                });
        if ($quantity > 0) {
            fail("第{$num}行库存数量不足！");
            }

        }
    }